package com.mmz.test.activemq;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.RedeliveryPolicy;

import javax.jms.*;
public class JmsReciver {
    public static void main(String args[]) throws Exception {
        Session session = null;
        Connection con = null;
        try {
            // 通过工厂模式获取链接
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
            // 设置重发策略
            RedeliveryPolicy redeliveryPolicy= new RedeliveryPolicy();
            redeliveryPolicy.setMaximumRedeliveries(5);
            redeliveryPolicy.setInitialRedeliveryDelay(3000);
            // 是否在每次尝试重新发送失败后,增长这个等待时间
            redeliveryPolicy.setUseExponentialBackOff(false);
            connectionFactory.setRedeliveryPolicy(redeliveryPolicy);
            con = connectionFactory.createConnection();
            con.start();
            // 创建会话（是否使用事务，消息确认机制）
            session = con.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建目的地（消息队列名称）
            Destination destination = session.createQueue("my-queue");
            // 创建消费者（消息接收器）
            MessageConsumer consumer = session.createConsumer(destination);

            // 接收消息
            while(true){
                TextMessage message = (TextMessage) consumer.receive();
                session.rollback();
                System.out.println("接收消息：" + message.getText());
                session.commit();

            }
//            for (int i = 0; i < 3; i++) {
//                TextMessage message = (TextMessage) consumer.receive();
//                session.rollback();
//
//                System.out.println("接收消息：" + message.getText());
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
            con.close();
        }
    }

}
